package com.joekai.base_library.http;

import com.google.gson.JsonParseException;
import com.joekai.base_library.BaseApp;
import com.joekai.base_library.R;
import com.joekai.base_library.utils.CommonUtil;
import com.joekai.base_library.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import retrofit2.HttpException;

/**
 * author:  JoeKai
 * date: 2022/6/30 21:50
 * content：
 */
public abstract class BaseObserver implements Observer<String> {

    boolean isNetWorkError = false;

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull String s) {
        try {
            if (HttpTool.isJsonObject(s)) {
                JSONObject jsonObject = new JSONObject(s);
                if (jsonObject.has(HttpConfigPlugin.getInstances().beanConfig.configCodeKey())) {
                    int code = jsonObject.getInt(HttpConfigPlugin.getInstances().beanConfig.configCodeKey());
                    if (code == HttpConfigPlugin.getInstances().beanConfig.configSuccessCode()) {
                        if (jsonObject.has(HttpConfigPlugin.getInstances().beanConfig.configDataKey())) {
                            String data = jsonObject.getString(HttpConfigPlugin.getInstances().beanConfig.configDataKey());
                            onSuccess(data);
                        }
                        if (jsonObject.has(HttpConfigPlugin.getInstances().beanConfig.configListKey())) {
                            String list = jsonObject.getString(HttpConfigPlugin.getInstances().beanConfig.configListKey());
                            onSuccess(list);
                        }
                    } else {
                        String msg = jsonObject.getString(HttpConfigPlugin.getInstances().beanConfig.configMessageKey());
                        onFail(code, msg, false);
                    }
                }
            } else {
                onFail(HttpConstant.JSON_ERROR, CommonUtil.getStrings(R.string.JSON_ERROR_MSG), false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onError(Throwable e) {
        Throwable throwable = e;
        String error = null;
        int errCode = 0;
        // 1.检查网络设置
        if (!HttpTool.hasNetwork(BaseApp.getInstance())) {
            onComplete();
            onFail(HttpConstant.NOT_NETWORK, CommonUtil.getStrings(R.string.NOT_NETWORK_MSG), true);
            return;
        }
        //获取最根源的异常
        while (throwable.getCause() != null) {
            e = throwable;
            throwable = throwable.getCause();
        }

        if (e instanceof ConnectException) {
            //网络连接失败
            errCode = HttpConstant.NOT_NETWORK;
            error = CommonUtil.getStrings(R.string.NOT_NETWORK_MSG);
            isNetWorkError = true;
        } else if (e instanceof HttpException) {
            //访问链接不存在
            HttpException httpException = (HttpException) e;
            errCode = HttpConstant.NOT_FOUND;
            error = httpException.getLocalizedMessage() + "";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException) {
            errCode = HttpConstant.JSON_ERROR;
            error = CommonUtil.getStrings(R.string.JSON_ERROR_MSG);
        } else if (e instanceof IOException) {
            if (e instanceof SocketTimeoutException) {
                errCode = HttpConstant.NOT_NETWORK;
                error = CommonUtil.getStrings(R.string.NOT_NETWORK_MSG);
                isNetWorkError = true;
            } else {
                if ("Canceled".equals(e.getMessage()) || "Socket closed".equals(e.getMessage())) {

                } else {
                    errCode = HttpConstant.NOT_NETWORK;
                    error = CommonUtil.getStrings(R.string.NOT_NETWORK_MSG);
                    isNetWorkError = true;
                }
            }
        } else {
            errCode = HttpConstant.OTHER;
            error = e.getLocalizedMessage();
        }
        try {
            if (HttpConfigPlugin.getInstances().httpConfig.showErrorToast()) {
                ToastUtil.showToast(error);
            }
            onFail(errCode, error, isNetWorkError);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    @Override
    public void onComplete() {

    }

    /**
     * ss
     *
     * @param result
     */
    protected abstract void onSuccess(String result);

    /**
     * ss
     *
     * @param code
     * @param msg
     */
    protected abstract void onFail(int code, String msg, boolean isNetWorkError);

}
